import router from '@/router'
import { getToken } from '@/utils/auth'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login'] // 白名单
const errorList = ['/401', '/404']

// 导航守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next({ path: '/', replace: true })
    } else if (errorList.includes(to.path)) {
      next()
    } else {
      try {
        const hasUserInfo = store.state.auth.name
        if (!hasUserInfo) {
          await store.dispatch('auth/getInfo')
        }
        if (to.name === 'home' || to.name === '/' || store.state.auth.menus.includes(to.name)) {
          next()
        } else {
          next('/401')
        }
      } catch (error) {
        // 重新登陆
        await store.dispatch('auth/resetToken')
        Message.error(error || 'Has Error')
        next('/login')
        NProgress.done()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
